package namespace

import (
	"context"
	log "github.com/sirupsen/logrus"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"strings"
	"twwch/k8s-admin/apis"
	"twwch/k8s-admin/application/base"
	"twwch/k8s-admin/models/common"
	"twwch/k8s-admin/models/namespace"
)

type NamespaceService struct {
	base.BaseService
}

var svc = &NamespaceService{}

func GetService() *NamespaceService {
	svc.Logger = log.WithField("service", "namespace")
	return svc
}

func (svc *NamespaceService) ListNamespace(ctx context.Context, req *namespace.ListReq) (*namespace.ListResp, error) {
	listOptions := metav1.ListOptions{}
	namespaces, err := apis.CoreV1().Namespaces().List(ctx, listOptions)
	if err != nil {
		svc.Logger.Error(ctx, err)
		return nil, err
	}
	resp := new(namespace.ListResp)
	names := make([]string, 0)
	for _, i := range namespaces.Items {
		if strings.Contains(i.Name, "kube") {
			continue
		}
		names = append(names, i.Name)
	}
	resp.Name = names
	return resp, nil
}

func (svc *NamespaceService) DeleteNamespace(ctx context.Context, req *namespace.DeleteReq) (*common.Empty, error) {
	err := apis.CoreV1().Namespaces().Delete(ctx, req.Name, metav1.DeleteOptions{})
	if err != nil {
		svc.Logger.Error(ctx, err)
	}
	return nil, err
}
